﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

namespace LdCms.Web.Controllers.MVC.Sms
{
    using LdCms.Common.Extension;
    using LdCms.Common.Security;
    using LdCms.Common.Time;
    using LdCms.EF.DbModels;
    using LdCms.IBLL.Sms;
    using LdCms.Plugins.Sms.Tencent;
    using LdCms.Web.Models;
    using LdCms.Web.Services;
    using LdCms.Common.Json;
    using LdCms.Web.Authorizes;

    /// <summary>
    /// 
    /// </summary>
    [AdminAuthorizeAttribute(Roles = "Admins")]
    public class SmsTencentPlatformController : BaseController
    {
        private readonly IBaseManager BaseManager;
        private readonly ITencentPlatformService TencentPlatformService;
        private readonly ITencentSendRecordService TencentSendRecordService;
        public SmsTencentPlatformController(IBaseManager BaseManager, ITencentPlatformService TencentPlatformService, ITencentSendRecordService TencentSendRecordService) : base(BaseManager)
        {
            this.BaseManager = BaseManager;
            this.TencentPlatformService = TencentPlatformService;
            this.TencentSendRecordService = TencentSendRecordService;
        }
        private Ld_Sms_TencentPlatform TencentPlatform
        {
            get
            {
                return TencentPlatformService.GetTencentPlatformByDefault(SystemID, CompanyID);
            }
        }
        private TencentSmsHelper TencentSmsHelper
        {
            get
            {
                
                string appid = TencentPlatform.AppID;
                string appkey = TencentPlatform.AppKey;
                return new TencentSmsHelper(appid, appkey);
            }
        }


        public override IActionResult Index()
        {
            return View();
        }
        public IActionResult List()
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.扩展管理.友情链接.列表);

                if (!IsPermission(funcId)) { return ToPermission(funcId); }
                var lists = TencentPlatformService.GetTencentPlatformAll(SystemID, CompanyID);
                ViewData["Count"] = TencentPlatformService.CountTencentPlatform(SystemID, CompanyID);
                return View(lists);
            }
            catch (Exception ex)
            {
                return ToError(ex.Message);
            }
        }
        public IActionResult Add(string platformId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(platformId))
                    return View(new Ld_Sms_TencentPlatform());
                var entity = TencentPlatformService.GetTencentPlatform(SystemID, CompanyID, platformId);
                if (entity == null)
                    return View(new Ld_Sms_TencentPlatform());
                return View(entity);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public IActionResult Send(string platformId)
        {
            try
            {
                var entity = TencentPlatformService.GetTencentPlatform(SystemID, CompanyID, platformId);
                string content = string.Empty;
                for (var i = 0; i < entity.ParamsQuantity; i++)
                {
                    int quantity = i + 1;
                    if (quantity == 1)
                        content = content + string.Format("参数{0}", quantity);
                    else
                        content = content + string.Format(",参数{0}", quantity);
                }
                ViewBag.Content = content;
                return View(entity);
            }
            catch (Exception ex)
            {
                return ToError(ex.Message);
            }
        }


        [HttpPost]
        public JsonResult Save(string platformId)
        {
            try
            {
                string fTitle = GetFormValue("fTitle");
                string fSign = GetFormValue("fSign");
                string fAppID = GetFormValue("fAppID");
                string fAppKey = GetFormValue("fAppKey");
                string fTplID = GetFormValue("fTplID");
                string fParamsQuantity = GetFormValue("fParamsQuantity");
                string fContent = GetFormValue("fContent");
                string fIsDefault = GetFormValue("fIsDefault");
                string fRemark = GetFormValue("fRemark");
                string fState = GetFormValue("fState");

                var primaryKey = PrimaryKeyHelper.PrimaryKeyType.SmsTencentPlatform;
                var primaryKeyLen = PrimaryKeyHelper.PrimaryKeyLen.V1;
                string createPlatformId = PrimaryKeyHelper.MakePrimaryKey(primaryKey, primaryKeyLen);
                string fPlatformId = string.IsNullOrEmpty(platformId) ? createPlatformId : platformId;

                var entity = new Ld_Sms_TencentPlatform();
                entity.SystemID = SystemID;
                entity.CompanyID = CompanyID;
                entity.PlatformID = fPlatformId;
                entity.PlatformName = "腾讯短信平台";
                entity.Title = fTitle;
                entity.Sign = fSign;
                entity.AppID = fAppID;
                entity.AppKey = fAppKey;
                entity.TplID = fTplID.ToInt();
                entity.ParamsQuantity = fParamsQuantity.ToInt();
                entity.Content = fContent;
                entity.Remark = fRemark;
                entity.IsDefault = fIsDefault.ToBool();
                entity.Remark = fRemark;
                entity.State = fState.ToBool();

                bool result = false;
                if (string.IsNullOrEmpty(platformId))
                    result = TencentPlatformService.SaveTencentPlatform(entity);
                else
                    result = TencentPlatformService.UpdateTencentPlatform(entity);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        [HttpPost]
        public JsonResult UpdateDefault(string platformId, bool state)
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.栏目管理.栏目分类.审核);
                if (!IsPermission(funcId)) { return Error("您没有操作权限，请联系系统管理员！"); }
                var result = TencentPlatformService.UpdateTencentPlatformDefault(SystemID, CompanyID, platformId, state);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        [HttpPost]
        public JsonResult Delete(string platformId)
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.栏目管理.栏目分类.删除);
                if (!IsPermission(funcId)) { return Error("您没有操作权限，请联系系统管理员！"); }

                var result = TencentPlatformService.DeleteTencentPlatform(SystemID, CompanyID, platformId);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        [HttpPost]
        public JsonResult SendSms(string platformId)
        {
            try
            {
                string fPhone = GetFormValue("fPhone");
                string fContent = GetFormValue("fContent");

                string[] sParams = fContent.Split(",");
                string sendId = GetSendId();
                string ext = new
                {
                    system_id = SystemID,
                    company_id = CompanyID,
                    platform_id = platformId,
                    send_id = sendId
                }.ToJson();
                var sendResult = SendSms(TencentPlatform, fPhone, ext, sParams);
                SaveSendRecord(TencentPlatform, fPhone, ext, sParams, sendId, sendResult);
                if (sendResult.result == 0)
                    return Success("ok");
                else
                    return Error(sendResult.errmsg);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        #region 私有方法
        private string GetSendId()
        {
            try
            {
                var primarykey = PrimaryKeyHelper.PrimaryKeyType.SmsTencentSendRecord;
                var primaryKeyLen = PrimaryKeyHelper.PrimaryKeyLen.V2;
                return PrimaryKeyHelper.MakePrimaryKey(primarykey, primaryKeyLen);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private string ToContent(string content, string[] sParams)
        {
            try
            {
                string result = content;
                for (var i = 0; i < sParams.Length; i++)
                {
                    result = result.Replace("{1}", sParams[i]);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private SendSmsResult SendSms(Ld_Sms_TencentPlatform entity, string mobile, string ext, string[] sParams)
        {
            try
            {
                string appid = entity.AppID;
                string appkey = entity.AppKey;
                int tplId = entity.TplID.ToInt();
                string sign = entity.Sign;
                return TencentSmsHelper.SendSmsPro(new SendSms()
                {
                    ext = ext,
                    tpl_id = tplId,
                    tel = new SendSmsTel() { nationcode = "86", mobile = mobile },
                    @params = sParams,
                    sign = sign,
                    time = TimeHelper.GetUnixTimestampTen()
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private void SaveSendRecord(Ld_Sms_TencentPlatform entity, string mobile, string ext, string[] sParams, string sendId, SendSmsResult sendSmsResult)
        {
            try
            {
                string appid = entity.AppID;
                string appkey = entity.AppKey;
                int tplId = entity.TplID.ToInt();
                string sign = entity.Sign;
                TencentSendRecordService.SaveTencentSendRecord(new Ld_Sms_TencentSendRecord()
                {
                    SystemID = entity.SystemID,
                    CompanyID = entity.CompanyID,
                    PlatformID = entity.PlatformID,
                    SendID = sendId,
                    Code = sParams[0].ToString(),
                    NationCode = "86",
                    Mobile = mobile,
                    Sign = sign,
                    Ext = ext,
                    //Extend="",
                    TplID = tplId,
                    Params = sParams.ToJson(),
                    Content = ToContent(entity.Content, sParams),
                    Time = TimeHelper.GetUnixTimestampTen(),
                    Fee = sendSmsResult.fee,
                    SId = sendSmsResult.sid,
                    ErrMsg = sendSmsResult.errmsg,
                    IsResult = sendSmsResult.result == 0 ? true : false,
                    CreateDate = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion


    }
}